from django.shortcuts import render
from apps.verifications.libs.captcha.captcha import captcha
from django.views import View
from django_redis import get_redis_connection
from django import http
import random,logging
from apps.verifications.libs.yuntongxun.ccp_sms import CCP
# Create your views here.

class SMSCodeView(View):
    """短信验证码
    GET /sms_codes/<mobile:mobile>/
    """
    def get(self,request,mobile):
        """
        实现发送短信逻辑
        :param request:
        :param mobile:
        :return: Json
        """
        # 接收参数
        image_code_client = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')

        # 校验参数
        if not all([image_code_client,uuid]):
            return http.JsonResponse({'code':400,'errmsg':'缺少必传参数'})

        # 提取图形验证码
        redis_conn = get_redis_connection('verify_code')
        image_code_server = redis_conn.get('img_%s'%uuid)
        # 判断是否过期
        if not image_code_server:
            return http.JsonResponse({'code':400,'errmsg':'图形验证码已过期'})

        # 删除图形验证码
        redis_conn.delete('img_%s'%uuid)

        # 对比图形验证码
        if image_code_server.lower().decode() != image_code_client:
            return http.JsonResponse({'code':400,'errmsg':'验证码有误'})

        # 生成短信验证码
        random_num = random.randint(0,999999)
        sms_code = '%06d'%random_num
        logging.info(sms_code)
        # sms_code = '%06d' % random.randint(0, 999999)

        # 保存短信验证码
        redis_conn = get_redis_connection('verify_code')
        # redis_conn.setex('sms_%s'%mobile,300,sms_code)

        # 往 redis 中写入一个数据, 写入什么不重要, 时间重要
        # 我们给写入的数据设置为60s,如果过期,则会获取不到.
        # redis_conn.setex('send_flag_%s' % mobile, 60, 1)

        # 管道的使用
        pl = redis_conn.pipeline()

        # redis_conn.setex('sms_%s' % mobile, 300, sms_code)
        pl.setex('sms_%s' % mobile, 300, sms_code)

        # redis_conn.setex('send_flag_%s' % mobile, 60, 1)
        pl.setex('send_flag_%s' % mobile, 60, 1)

        # 执行管道:
        pl.execute()

        # 发送短信验证码
        # CCP().send_template_sms('测试的手机号', ['短信验证码', 时间], 模板id)
        CCP().send_template_sms(mobile,[sms_code,5],1)

        # 响应结果
        return http.JsonResponse({'code':0,'errmsg':'发送完成'})


class ImageCodeView(View):
    """图形验证码
    GET http://www.meiduo.site:8080/image_codes/<uuid>/
    """
    def get(self,request,uuid):
        """
        图形验证码逻辑
        :param request:
        :param uuid:
        :return:
        """

        # 生成图形验证码
        text,image = captcha.generate_captcha()

        # 保存图形验证码
        # 使用redis数据库别名，创建链接到redis
        redis_conn = get_redis_connection('verify_code')

        # 使用连接到redis的对象去操作数据存储到redis
        # redis_conn.setex('key','过期时间','value')
        redis_conn.setex('img_%s'%uuid,300,text)

        # 响应图形验证码image/jpg
        return http.HttpResponse(image,content_type='image/jpg')